// 路由守卫注册
import { SYSTEM_TITLE } from "@/constant"
import projectSetting from "@/settings/projectSetting"
import { AxiosCanceler } from '@/utils/http/axios/axiosCancel';
import { message, notification } from "ant-design-vue"
import { Message, Notification } from "element-ui"

const { routerGuardSetting } = projectSetting;

export function setupRouterGuard(router) {
    createHttpGuard(router)
    createScrollGuard(router)
    createMessageGuard(router)
    createDocumentTitleGuard(router)
    createToErrorPageGuard(router)
}

// 在路由切换时，先将pending状态的接口取消掉
function createHttpGuard(router) {
    let axiosCanceler
    if (routerGuardSetting.removeAllHttpPendingOnSwitch) {
        axiosCanceler = new AxiosCanceler();
    }
    router.beforeEach(async (to, from, next) => {
        if (axiosCanceler) {
            await axiosCanceler.removeAllPending();
        }
        next()
        return true
    })
}
// 在路由切换后将滚动条滚动到顶部
function createScrollGuard(router) {
    if (routerGuardSetting.scrollToTopOnSwitch) {
        const html = document.getElementsByTagName('html')[0]
        router.afterEach(async () => {
            html.scrollTo(0, 0)
            return true
        })
    }
}
// 在路由切换后关闭现有的消息提示
function createMessageGuard(router) {
    router.beforeEach(async (to, from, next) => {
        try {
            if (routerGuardSetting.closeMessageOnSwitch) {
                // antdv的消息提示关闭
                message.destroy()
                notification.destroy()

                // elementui的消息提示关闭
                Message.closeAll()
                Notification.closeAll()
            }
        } catch (error) {
            warn('message guard error:' + error);
        }
        next()
        return true;
    })
}
// 在路由切换时，修改浏览器title
function createDocumentTitleGuard(router) {
    router.afterEach((to) => {
        document.title = SYSTEM_TITLE + (to.meta?.title ? `-${to.meta.title}` : '')
    })
}
// 在路由切换时，根据错误信息重定向路由
function createToErrorPageGuard(router) {
    router.beforeEach((to, from, next) => {
        // 如果访问的页面不存在，重定向到404
        if (to.matched.length === 0) {
            next('/404')
        } else {
            next()
        }
    })
}


